#include "CreateCommand.h"
#include <iostream>
#include <boost\tokenizer.hpp>
using namespace std;
using namespace boost;

CreateCommand::CreateCommand(SQLSystem* sql): Command(sql)
{
}


CreateCommand::~CreateCommand()
{
}

int CreateCommand::execute(string str)
{
	Table* newTable= new Table;	//create new table in the freestore(heap)
	
	//begin using tokenizer class of boost library
	char_separator<char> sep(" ","(),",drop_empty_tokens);	//create a char_separator to define delimiters
	//the first two are delimiters used to token the string. the second param is keep_delimiters that still show in output

	tokenizer<char_separator<char>> tok(str, sep);	//create a tokenizer for the statement with the defined delimiters
	tokenizer<char_separator<char>>::iterator tok_iter=tok.begin();	//iterator for traverse through tokens
	++tok_iter;	//increment 'cause the first one already determined("CREATE")
	cout << "CREATING TABLE...\n";
	if(tok_iter == tok.end())	
		return false;
	if(helper->toUpperString(*tok_iter)!="TABLE")	//"TABLE" follows "CREATE"
		return false;
	++tok_iter;
	if(tok_iter == tok.end())	
		return false;
	//name of the table
	newTable->setName(*tok_iter);
	++tok_iter;
	if(tok_iter == tok.end())	
		return false;
	while(*tok_iter!=")")
	{
		++tok_iter;
		//column name part
		//just one-word name column
		if(tok_iter!=tok.end())
		{
			newTable->addColumn(*tok_iter);
		}
		else
			return false;
		++tok_iter;
		//column type part
		if(tok_iter!=tok.end())
		{
			//check for the type of the column and add the appropriate constant
			//notice the use of helper method 'cause SQL is not case-sensitive
			if(helper->toUpperString(*tok_iter) =="VARCHAR")
				newTable->addType(VARCHAR);
			else if(helper->toUpperString(*tok_iter) =="INT")
				newTable->addType(INT);
			else
			{
				cout << "Unsupported type\n";
				return false;
			}
		}
		else
			return false;
		++tok_iter;
		if(tok_iter == tok.end())	
			return false;
		//check if end of command or end of the current column
		if(*tok_iter==",")
			continue;
		if(*tok_iter==")")
			break;
		//constraint part
		cout << "CONSTRAINTS: ";
		while(*tok_iter!="," && *tok_iter!=")")
		{
			cout << *tok_iter++ << " ";
		}			
		cout << endl;
	}
	cout << "FINISH CREATING TABLE.\n" << endl;
	SQLSystem* sys= getSystem();
	sys->addTable(newTable);
	return true;
	
}

